/**
 * Created by Kiva on 17/1/22.
 */
(function ($) {
    "use strict";
    $.fn.extend({
        grayTable:function(setting,callback) {
            this.options =$.extend({},$.fn.grayTable.options,setting);
            callback = callback || function () {};
            grayTableCreate(this,callback,setting);
            return this;
        }
    });

    $.fn.grayTable.options={
        param : {},//url请求参数
        method:"get",
        onLoadSuccess:function (data) {},
        pageSize:[8,15,30,100],
        selectOption:15,
        filter:[],
        column:[],
        rowClick: function($tr,row){},//单击行的事件
        endTableCreate:function (data){}//表格完成之后的回调函数
    };

    function grayTableCreate($gray_table,fn,setting) {
        var options=$gray_table.options,
            pageFlag=!!$gray_table.options.paging,
            rowData;
		initTable();
        function initTable() {
			//未定义任何表格列，直接返回
			if (options.column == undefined || options.column.length == 0) {
				return;
			}
            var $table=$gray_table.find("table:first");
            var $grayBody=$gray_table.find("div.gray-table-body");
            $grayBody.find(".page").remove();
            $grayBody.find(".page-size").remove();
			initTableThead($table);
			if(pageFlag){
                initPageSize($grayBody);
            }

			$grayBody.append("<div class='page'></div>");
            var $tbody=$table.find("tbody:first");
            var $page=$gray_table.find("div.page:first");
            var arrowLeft="iconfont icon-jiantou3";
            var arrowRight="iconfont icon-iconfontjiantou6";
            var arrow={
                    arrowArr:[arrowLeft,arrowRight]
                };
			//表格未找到tbody
            if($tbody.length < 1){
                $table.append("<tbody></tbody>");
                $tbody=$table.find("tbody:first");
            }
            arrow[arrowLeft]=-1;
            arrow[arrowRight]=1;
            if(pageFlag){
                addPageSizeEvent($tbody, $page, arrow);
                addPageNumEvent($tbody, $page, arrow);
            }
            addFilterEvent($tbody, $page, arrow);
            loadTable($tbody, $page, arrow);
            addTrClickEvent($tbody);
        }
		//生成表头
		function initTableThead($table) {
            var html="<thead><tr>";
			$(options.column).each(function(index, column){
                if (column.title == undefined || column.title == "") {
                    html+=`<td colspan="${column.colspan}" title="${column.html}">${column.html}</td>`;
                } else {
                    html+=`<td colspan="${column.colspan}" title="${column.title}">${column.title}</td>`;
                }
			});
			html+="</tr></thead>";
			html+="<tbody></tbody>";
			$table.html(html);
		}

		//生成每页显示页数
        function initPageSize($grayBody) {
            var html='<div class="page-size pull-left"><span>每页显示条数:</span><select class="form-control pull-right record-page">';
            $.each($gray_table.options.pageSize,function (i,v) {
                var v=parseInt(v);
                if(v && v>0){
                    html+='<option value="'+v+'">'+v+'</option>';
                }
            });
            html+='</select></div>';
            $grayBody.append(html);
            if($gray_table.options.selectOption){
            	$grayBody.find("div.page-size").find("select:first").val($gray_table.options.selectOption);
            }else{
                setting.selectOption=$gray_table.options.selectOption=$gray_table.options.pageSize[0];
            }
            
            setting.param[$gray_table.options.paging.pageSize]=$gray_table.options.param[$gray_table.options.paging.pageSize]=$gray_table.options.selectOption;
        }

        // 记录每次修改页面
        $(".record-page").on("change", function() {
            sessionStorage.setItem("recordPage", $(this).val())
        })

        //根据套餐加载套餐明细的方法
        function loadTable($tbody, $page, arrow) {
            $.ajax({
                url:options.url,
                dataType:"json",
                type:options.method,
                async:false,
                data: options.param,
                success:function (data) {
                	if(data.ret==1)
                    {
                        layer.msg(data.msg);
                    }
                    else
                    {
	                    options.onLoadSuccess(data);
	                    var html="";
	                    rowData=data.rows||data.data;
	                    // rowData=data.rows;
	                    if(!rowData) return;
	                    // if(!data.rows) return;
	                    // $.each(data.rows,function (i,value) {
	                    $.each(rowData,function (i,value) {
	                        html+='<tr ';
	                        for(var _attr in options.attribute){
	                            html+=_attr+'='+value[options.attribute[_attr]]+" ";
	                        }
	                        html+=">";
	                        var _data=value;
	                        var index=i;
	                        $.each(options.column,function (i,value) {
	                            html+='<td colspan='+value.colspan+'>';
	                            if(value.format){
	                                html+=value.format(_data,index);
	                            }else if(value["text"] != undefined){
	                                var tempData=_data;
	                                $.each(value["text"].toString().split("."),function (i,v) {
	                                	if(String(tempData[v])==="0" || tempData[v]){
	                                		tempData=tempData[v];
	                                	}else{
	                                		tempData="";
	                                	}
	                                });
	                                html+=tempData;
	                            }
								if (options.column[i]["html"] != undefined) {
									html+=options.column[i]["html"];
								}
	                            html+='</td>';
	                        });
	                        html+='</tr>';
	                    });
	                    $tbody.html(html);
	                    if (pageFlag){
	                        setPageTotal(data["total"]);
	                        addPageNum($page,arrow);
	                    }
	                    fn(data);
                        options.endTableCreate(data)
                    }
                },
                error:function () {
                	layer.msg("请求出现例外:" + jqXHR.statusText);
                }
            });
        }

        //根据数据添加分页html代码
        function addPageNum($page,arrow) {
            var html='<span><i class="'+arrow.arrowArr[0]+'"></i></span>';
            var pageNum=options.param[options.paging.pageNum];
            var pageTotal=options.paging.pageTotal;
            if(pageTotal<=5){
                for(var i=1;i<=pageTotal;i++){
                    html+='<span>'+i+'</span>';
                }
            }else{
                if(pageNum-1<=2){
                    for(var i=1;i<=4;i++){
                        html+='<span>'+i+'</span>';
                    }
                    html+='<span>...</span><span>'+pageTotal+'</span>';
                }else if(pageTotal-pageNum<=2){
                    html+='<span>1</span><span>...</span><span>'+(pageTotal-3)+'</span><span>'+(pageTotal-2)+'</span><span>'+(pageTotal-1)+'</span><span>'+pageTotal+'</span>';
                }else{
                    html+='<span>1</span><span>...</span><span>'+(pageNum-1)+'</span><span>'+pageNum+'</span><span>'+(pageNum+1)+'</span><span>...</span><span>'+pageTotal+'</span>';
                }
            }
            html+='<span><i class="'+arrow.arrowArr[1]+'"></i></span>';
            $page.html(html);
            $page.children("span").each(function () {
                var $span=$(this);
                var text=$span.text();
                if(text==pageNum){
                    $span.addClass("page-focus");
                } else if(text=="..."){
                    $span.addClass("page-n-focus");
                }
            });
        }

        //给点击页数的按钮添加事件
        function addPageNumEvent($tbody,$page,arrow) {
            if(!options.param[options.paging.pageNum]){
                options.param[options.paging.pageNum]=1;
            }
            $page.on("click","span",function (e) {
                var pageNum=parseInt(options.param[options.paging.pageNum]),
                    pageTotal=parseInt(options.paging.pageTotal),
                    $target=$(e.target),
                    number=parseInt($target.text()),
                    pageNumNext,
                    $i;
                $i=$target.hasClass("iconfont")?$target:$target.find("i");
                pageNumNext=pageNum+parseInt(arrow[$i.context.className]);
                if(number===number && pageNum!==number){
                    options.param[options.paging.pageNum]=number;
                    loadTable($tbody,$page,arrow);
                }else if($i.length>0 && pageNumNext>=1 && pageNumNext<=pageTotal){
                    options.param[options.paging.pageNum]=pageNum+arrow[$i.context.className];
                    loadTable($tbody,$page,arrow);
                }
            });
        }

        function setPageTotal(total) {
            var pageSize=parseInt($gray_table.options.param[$gray_table.options.paging.pageSize]);
            total=parseInt(total);
            if(total%pageSize>0){
                $gray_table.options.paging["pageTotal"]=parseInt(total/pageSize)+1;
            }else{
                $gray_table.options.paging["pageTotal"]=total/pageSize;
            }
        }

        //给顶层的过滤input添加事件
        function addFilterEvent($tbody,$page,arrow){
            $.each(options.filter,function (i,v) {
                var $input=$gray_table.find(v["selector"]);
                $input.off("keydown.gray-table propertychange.gray-table");
                $input.on("keydown.gray-table propertychange.gray-table",function (e) {
                    if (e.keyCode == 13) {
                        setting.param[$input.attr("name")]=options.param[$input.attr("name")]=$input.val();
                        loadTable($tbody,$page,arrow);
                    }
                });
            });
        }
        //给左下角的select添加事件
        function addPageSizeEvent($tbody,$page,arrow) {
            var $pageSizeSelect=$gray_table.find(".page-size").find("select");
            setting.param[options.paging.pageSize]=options.param[options.paging.pageSize]=$pageSizeSelect.val();
            $pageSizeSelect.on("change",function () {
                setting.selectOption=options.param[options.paging.pageSize]=$pageSizeSelect.val();
                loadTable($tbody,$page,arrow);
            });
        }

        function addTrClickEvent($tbody) {
            $tbody.on("click","tr",function (e) {
                if(!$(e.target).is("input") && !$(e.target).is("select")){
                    var $tr=$(e.target).parents("tr:first"),
                        flag,
                        row={};
                    $.each(rowData,function (index) {
                        flag=true;
                       for(var i in options.attribute){
                           if(String(rowData[index][options.attribute[i]])!=$tr.attr(i)){
                               flag=false;
                               break;
                           }
                       }
                       if(flag){
                           row=rowData[index];
                           return false;
                       }
                    });
                    options.rowClick($tr,row);
                }
            });
        }

    }
}(jQuery));
